<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">智能快递管理系统</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="text" @click="verify" id="verifyButton" class="custom-verify-button"><i
          class="el-icon-circle-plus" style="color: #007BFF;">{{ verifyText }}</i></el-button>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <br>
      <el-button type="text" @click="forgetPassword">验证码登录</el-button>
      <div style="float: right;" v-if="register">
        <router-link class="link-type" :to="'/register'">立即注册</router-link>
      </div>
      <div style="display: flex; align-items: center;">
        <h1 class="customer-management-title"></h1>
      </div>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
<!--      <div style="width: 49px;height: 49px;margin-top: 5px;cursor: pointer;display: inline-block" title="微信登录"-->
<!--           @click="loginByWx">-->
<!--        <img style="height: 100%;width: 100%;" src="../assets/logo/weixin.jpg">-->
<!--      </div>-->
    </el-form>

    <el-dialog title="手机验证码登录" :visible.sync="dialogFormVisible" style="width: 80%" class="login-container">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="loginForm.code" placeholder="请输入验证码">
            <template slot="append">
              <el-button type="text" @click="sendCode" :disabled="sendCodeDisabled">{{ sendCodeText }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="text" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import {getCodeImg, findUsername} from "@/api/login";
import Cookies from "js-cookie";
import {encrypt, decrypt} from '@/utils/jsencrypt'
import * as faceapi from 'face-api.js';
import axios from "axios";
import {login, sendSms} from "../api/login";
import * as wx from "../api/login";

export default {
  name: "Login",
  data() {
    return {
      dialogFormVisible: false,
      flag2: false,
      flag: true,
      flag1: false,
      isLoaded: false,
      lastDetections: [], // 上一帧检测到的人脸
      peopleCount: 0, // 当前人流量计数
      id: this.$route.query.id,
      codeUrl: "",
      loginForm: {
        phone: '',
        code: ''
      },
      loginRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      sendCodeDisabled: false,
      sendCodeText: '获取验证码',
      countdown: 60,
      timer: null,
      loading: false,
      captchaEnabled: false,
      register: true,
      redirect: undefined,
      verifyText: '点击按钮进行验证',
      isVerified: false,
      isToken: localStorage.getItem('isToken')
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    forgetPassword(){
      this.dialogFormVisible=true;
    },
    sendCode() {
      const phoneNumber = this.loginForm.phone;
      if (!phoneNumber) {
        this.$message.warning('请先输入手机号');
        return;
      }

      sendSms(phoneNumber)
        .then((response) => {
          if (response.data.success) {
            this.$message.success('验证码已发送，请查收');
            this.startCountdown();
            // 确保这里正确存储令牌到form对象的token字段
            this.form.token = response.data.token;
          } else {
            this.$message.error(response.data.message);
          }
        })
        .catch((error) => {
          this.$message.error('发送验证码失败');
        });
    },
    startCountdown() {
      this.sendCodeDisabled = true;
      this.sendCodeText = `${this.countdown}秒后重发`;
      this.timer = setInterval(() => {
        this.countdown--;
        this.sendCodeText = `${this.countdown}秒后重发`;
        if (this.countdown === 0) {
          this.stopCountdown();
        }
      }, 1000);
    },
    stopCountdown() {
      clearInterval(this.timer);
      this.sendCodeDisabled = false;
      this.sendCodeText = '获取验证码';
      this.countdown = 60;
    },
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          const { phoneNumber, code } = this.form;
          sendSms(phoneNumber)
            .then((response) => {
              if (response.data.success) {
                this.$message.success('登录成功');
                this.$router.push('/home');
              } else {
                this.$message.error(response.data.message);
              }
            })
            .catch((error) => {
              this.$message.error('登录失败');
            });
        } else {
          this.$message.warning('请检查输入信息是否正确');
        }
      });
    },
    // sendCode() {
    //   const phoneNumber = this.loginForm.phone;
    //   if (!phoneNumber) {
    //     this.$message.warning('请先输入手机号');
    //     return;
    //   }
    //
    //   // 调用后端接口发送验证码，这里假设接口路径为 /auth/sendMessage/{phoneNumber}
    //   this.axios.post(`/auth/sendMessage/${phoneNumber}`)
    //     .then((response) => {
    //       if (response.data.success) {
    //         this.$message.success('验证码已发送，请查收');
    //         this.startCountdown();
    //       } else {
    //         this.$message.error(response.data.message);
    //       }
    //     })
    //     .catch((error) => {
    //       this.$message.error('发送验证码失败');
    //     });
    // },
    // startCountdown() {
    //   this.sendCodeDisabled = true;
    //   this.sendCodeText = `${this.countdown}秒后重发`;
    //   this.timer = setInterval(() => {
    //     this.countdown--;
    //     this.sendCodeText = `${this.countdown}秒后重发`;
    //     if (this.countdown === 0) {
    //       this.stopCountdown();
    //     }
    //   }, 1000);
    // },
    // stopCountdown() {
    //   clearInterval(this.timer);
    //   this.sendCodeDisabled = false;
    //   this.sendCodeText = '获取验证码';
    //   this.countdown = 60;
    // },
    // login() {
    //   this.$refs.loginForm.validate((valid) => {
    //     if (valid) {
    //       const { phoneNumber, code } = this.loginForm;
    //
    //       // 调用后端接口进行手机号验证码登录，这里假设接口路径为 /auth/loginByPhoneCode
    //       this.axios.post('/auth/loginByPhoneCode', { phoneNumber, code })
    //         .then((response) => {
    //           if (response.data.success) {
    //             this.$message.success('登录成功');
    //             // 登录成功后，获取并存储若依自带登录机制中的token，这里假设后端返回的格式为 { token: 'xxxxxx' }
    //             const token = response.data.token;
    //             localStorage.setItem('token', token);
    //             this.$router.push('/home');
    //           } else {
    //             this.$message.error(response.data.message);
    //           }
    //         })
    //         .catch((error) => {
    //           this.$message.error('登录失败');
    //         });
    //     } else {
    //       this.$message.warning('请检查输入信息是否正确');
    //     }
    //   });
    // },
    resetForm() {
      this.$refs.loginForm.resetFields();
      this.stopCountdown();
    }
  },
  beforeDestroy() {
    this.stopCountdown();
  },

    resetForm() {
      this.$refs.loginForm.resetFields();
      this.stopCountdown();
    },
    loginByGitee() {
      PreLoginByGitee().then(res => {
        Cookies.set("user-uuid", res.uuid)
        window.location = res.authorizeUrl
      });
    },
    verify() {
      this.isVerifying = true;
      this.verifyText = '正在验证...';
      setTimeout(() => {
        this.isVerifying = false;
        this.isVerified = true;
        this.verifyText = '验证成功';
      }, 2000);
    },
    // login() {
    //   if (this.isVerified) {
    //     console.log('登录成功')
    //   } else {
    //     console.log('请先验证')
    //   }
    // },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {expires: 30});
            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30});
            Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              // this.getCode();
            }
          });
        }
      });
    },
    // verifyButtonClick() {
    //   const verifyButton = document.getElementById('verifyButton');
    //   verifyButton.classList.add('clicked');
    //   verifyButton.disabled = true; // 可选：禁用按钮，防止重复点击
    // }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.face-recognition {
  position: relative;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
}
.login-container {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #e4e4e4;
  border-radius: 4px;
  background-color: #f9f9f9;
}

</style>
